//
//  CategoryViewController.m
//  MyTravel
//
//  Created by Hunk on 11-5-27.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "CategoryViewController.h"
#import "AsyncLoadingImageView.h"
#import "JourneyMenuViewController.h"
#import "NetworkManager.h"
#import "MyLoadingView.h"
#import "BottomView.h"
#import "NSString+URLEncoding.h"

#define TAG_ACTIVITYINDICATORVIEW 13
#define TAG_TABLEVIEW 15

@interface CategoryViewController (Private)

-(void)addLabelOnCell:(UITableViewCell*)cell 
				 text:(NSString*)text
				frame:(CGRect)frame 
			  bgColor:(UIColor*)bgColor 
			textColor:(UIColor*)textColor 
		   fontOfSize:(UIFont*)fontOfSize 
		lineBreakMode:(UILineBreakMode)lineBreakMode
		textAlignment:(UITextAlignment)textAlignment;

@end

@implementation CategoryViewController
@synthesize categoryId;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Init data
    arrayDepartmentNews = [[NSMutableArray alloc] init];
    bIsLoading = NO;
    
    // Init tableView
	UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 416) 
                                                          style:UITableViewStylePlain];
    //tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    tableView.delegate = self;
	tableView.dataSource = self;
    [tableView setTag:TAG_TABLEVIEW];
	[self.view addSubview:tableView];
    
    if (!_refreshHeaderView) 
    {	
		EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - tableView.bounds.size.height, self.view.frame.size.width, tableView.bounds.size.height)];
		view.delegate = self;
		[tableView addSubview:view];
		_refreshHeaderView = view;
		[view release];
		
	}
	
	//  update the last update date
	[_refreshHeaderView refreshLastUpdatedDate];

    [tableView release];
    
    // Data
    // NetworkRequest_GetJourneyNewsByCategoryId
    m_nCurrentPageNumber = 1;
    NSDictionary* parameters = [NSDictionary dictionaryWithObjectsAndKeys:
                                categoryId, @"category_id",
                                [NSString stringWithFormat:@"%d", 1], @"page_number", 
                                [NSString stringWithFormat:@"%d", PAGE_SIZE_JOURNEY], @"page_size", nil];
    
    [[NetworkManager sharedNetworkManager] requestServerForMethod:NetworkRequest_GetJourneyNewsByCategoryId
                                                   WithParameters:parameters
                                                 AndCallBackScope:self
                                                    AndSuccessSel:@"onSuccess:"
                                                     AndFailedSel:@"onFailed:"];
    [[MyLoadingView sharedMyLoadingView] startLoadingAnimation];
}

#pragma mark -
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    return [arrayDepartmentNews count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{	
	return 80.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
	static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                   reuseIdentifier:CellIdentifier] autorelease];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleBlue;

    // Cell Background view
    UIView* cellBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
    UIImageView* bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
    [bgImageView setImage:[[UIImage imageNamed:@"CellBackground.png"] 
                           stretchableImageWithLeftCapWidth:5 topCapHeight:5]];
    [cellBgView addSubview:bgImageView];
    [bgImageView release];
    [cell setBackgroundView:cellBgView];
    [cellBgView release];
    
    // Get one news
    NSDictionary* newsDictionary = [arrayDepartmentNews objectAtIndex:indexPath.row];
    
    // Load and add imageView
    AsyncLoadingImageView* asyncLoadingImageView = [[[AsyncLoadingImageView alloc] initWithFrame:CGRectMake(10, 10, 90, 60)] autorelease];
    asyncLoadingImageView.layer.cornerRadius = CORNERRADIUS_NEWS;
    asyncLoadingImageView.layer.masksToBounds = YES;
    NSString* imageString = PATH_JOURNEYBASEINFO_IMAGE([[newsDictionary objectForKey:KEY_TITLE] URLEncodedString] ,[newsDictionary objectForKey:KEY_IMAGE]);
    [asyncLoadingImageView loadImageFromURLString:imageString 
                                 placeholderImage:nil];
    [cell.contentView addSubview:asyncLoadingImageView];
    
    // Title
    [self addLabelOnCell:cell 
                    text:[newsDictionary objectForKey:KEY_TITLE] 
                   frame:CGRectMake(110, 0, 200, 30) 
                 bgColor:[UIColor clearColor] 
               textColor:[UIColor blackColor] 
              fontOfSize:[UIFont systemFontOfSize:16] 
           lineBreakMode:UILineBreakModeTailTruncation 
           textAlignment:UITextAlignmentLeft];
    
    // Time
    [self addLabelOnCell:cell 
                    text:[NSString stringWithFormat:@"出发日期：%@", [newsDictionary objectForKey:KEY_STARTINGTIME]] 
                   frame:CGRectMake(110, 32, 170, 20) 
                 bgColor:[UIColor clearColor] 
               textColor:[UIColor blackColor] 
              fontOfSize:[UIFont fontWithName:@"AmericanTypewriter" size:14]
           lineBreakMode:UILineBreakModeTailTruncation 
           textAlignment:UITextAlignmentLeft];
    
    // Address
    [self addLabelOnCell:cell 
                    text:[NSString stringWithFormat:@"出发地点：%@", [newsDictionary objectForKey:KEY_STARTINGADDRESS]] 
                   frame:CGRectMake(110, 55, 100, 20) 
                 bgColor:[UIColor clearColor] 
               textColor:[UIColor darkGrayColor] 
              fontOfSize:[UIFont italicSystemFontOfSize:14] 
           lineBreakMode:UILineBreakModeTailTruncation 
           textAlignment:UITextAlignmentLeft];
    
    // Price
    [self addLabelOnCell:cell 
                    text:[NSString stringWithFormat:@"¥%@", [newsDictionary objectForKey:KEY_PRICE]] 
                   frame:CGRectMake(225, 55, 80, 20) 
                 bgColor:[UIColor clearColor] 
               textColor:[UIColor redColor] 
              fontOfSize:[UIFont fontWithName:@"AmericanTypewriter" size:18]
           lineBreakMode:UILineBreakModeTailTruncation 
           textAlignment:UITextAlignmentLeft];
    
    return cell;
}

#pragma mark -
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // Go to journeyMenuViewController
    JourneyMenuViewController* journeyMenuViewController = [JourneyMenuViewController alloc];
    journeyMenuViewController.hidesBottomBarWhenPushed = YES;
    journeyMenuViewController.titleForHeader = [[arrayDepartmentNews objectAtIndex:indexPath.row] objectForKey:@"title"];
    journeyMenuViewController.journeyId = [[arrayDepartmentNews objectAtIndex:indexPath.row] objectForKey:@"journeyId"];
    [self.navigationController pushViewController:journeyMenuViewController animated:YES];
    [journeyMenuViewController release];
}

#pragma mark -
#pragma mark NetworkManager callback Methods
- (void)onSuccess:(id)sender
{
    NSDictionary* resultDic = (NSDictionary*)sender;
    
    m_nJourneyCount = [[resultDic objectForKey:@"count"] intValue];
    
    m_nCurrentPageNumber = 1;
    
    UITableView* tableView = (UITableView*)[self.view viewWithTag:TAG_TABLEVIEW];
    
    // Get journey list
    [arrayDepartmentNews removeAllObjects];
    [arrayDepartmentNews addObjectsFromArray:[resultDic objectForKey:@"journeyList"]];
    
    [tableView reloadData];
}

- (void)onFailed:(id)sender
{
    NSDictionary* resultDic = (NSDictionary*)sender;
    
    if([[resultDic objectForKey:@"message"] isEqualToString:@"No Data!"])
    {
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"服务器正在维护中，敬请期待"
                                                            message:nil
                                                           delegate:self
                                                  cancelButtonTitle:@"好的"
                                                  otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
    else
    {
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:SORRY_NODATA
                                                            message:[resultDic objectForKey:@"message"]
                                                           delegate:self
                                                  cancelButtonTitle:@"好的"
                                                  otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
}

#pragma mark -
#pragma mark addLabelOnCell
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark Callback Methods for More button 
- (void)onSuccessForMore:(id)sender
{
    bIsLoading = NO;
    
    NSDictionary* resultDic = (NSDictionary*)sender;
    
    UITableView* tableView = (UITableView*)[self.view viewWithTag:TAG_TABLEVIEW];
    
    m_nJourneyCount = [[resultDic objectForKey:@"count"] intValue];
    
    // Get journey list
    [arrayDepartmentNews addObjectsFromArray:[resultDic objectForKey:@"journeyList"]];
    
    [tableView reloadData];
}

- (void)onFailedForMore:(id)sender
{
    bIsLoading = NO;
    
    m_nCurrentPageNumber -= 1;
    
    NSLog(@"已经是最后一页了\n");
}

#pragma mark -
#pragma mark Data Source Loading / Reloading Methods
- (void)reloadTableViewDataSource
{
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	bIsLoading = YES;
    
    // 添加下拉刷新
    // Refresh
    m_nCurrentPageNumber = 1;
    NSDictionary* parameters = [NSDictionary dictionaryWithObjectsAndKeys:
                                categoryId, @"category_id",
                                [NSString stringWithFormat:@"%d", 1], @"page_number", 
                                [NSString stringWithFormat:@"%d", PAGE_SIZE_JOURNEY], @"page_size", nil];
    
    [[NetworkManager sharedNetworkManager] requestServerForMethod:NetworkRequest_GetJourneyNewsByCategoryId
                                                   WithParameters:parameters
                                                 AndCallBackScope:self
                                                    AndSuccessSel:@"onSuccess:"
                                                     AndFailedSel:@"onFailed:"];
}

- (void)doneLoadingTableViewData
{	
	//  model should call this when its done loading
	bIsLoading = NO;
    
    UITableView* tableView = (UITableView*)[self.view viewWithTag:TAG_TABLEVIEW];
    
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:tableView];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{		
    [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
    if(((scrollView.contentOffset.y + scrollView.frame.size.height) > scrollView.contentSize.height - 30)&& !bIsLoading)
    {   
        // If current page number > total page number
        if(m_nCurrentPageNumber + 1 > ((m_nJourneyCount % PAGE_SIZE_JOURNEY) == 0 ? (m_nJourneyCount/PAGE_SIZE_JOURNEY):(m_nJourneyCount/PAGE_SIZE_JOURNEY + 1)))
        {
            if((int)scrollView.contentOffset.y % 20 == 0)
            {
                BottomView* bottomView = [[BottomView alloc] initWithFrame:CGRectMake(10, 386, 300, 30) 
                                                                      name:@"已经是最后一页了"];
                [self.view addSubview:bottomView];
                
                [bottomView bottomViewWillAppear];
                
                [bottomView release];
            }
        }
        else
        {
            bIsLoading = YES;
            
            // 上拉刷新
            m_nCurrentPageNumber += 1;
            
            NSDictionary* parameters = [NSDictionary dictionaryWithObjectsAndKeys:
                                        categoryId, @"category_id",
                                        [NSString stringWithFormat:@"%d", m_nCurrentPageNumber], @"page_number", 
                                        [NSString stringWithFormat:@"%d", PAGE_SIZE_JOURNEY], @"page_size", nil];
            
            [[NetworkManager sharedNetworkManager] requestServerForMethod:NetworkRequest_GetJourneyNewsByCategoryId
                                                           WithParameters:parameters
                                                         AndCallBackScope:self
                                                            AndSuccessSel:@"onSuccessForMore:"
                                                             AndFailedSel:@"onFailedForMore:"];
            
            NSString* nameString = [NSString stringWithFormat:@"正在加载第%d页", m_nCurrentPageNumber];
            
            BottomView* bottomView = [[BottomView alloc] initWithFrame:CGRectMake(10, 386, 300, 30) 
                                                                  name:nameString];
            [self.view addSubview:bottomView];
            
            [bottomView bottomViewWillAppearWithDuration:2.0];
            
            [bottomView release];
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{	
//    if((scrollView.contentOffset.y + scrollView.frame.size.height) > scrollView.contentSize.height + 20 )//&& bIsLoading)
//    {
//        // If current page number > total page number
//        if(m_nCurrentPageNumber + 1 > ((m_nJourneyCount % PAGE_SIZE_JOURNEY) == 0 ? (m_nJourneyCount/PAGE_SIZE_JOURNEY):(m_nJourneyCount/PAGE_SIZE_JOURNEY + 1)))
//        {
//            NSLog(@"onSuccessForMore已经是最后一页了\n");    
//        }
//        else
//        {
//            bIsLoading = YES;
//            
//            // 上拉刷新
//            m_nCurrentPageNumber += 1;
//            
//            NSDictionary* parameters = [NSDictionary dictionaryWithObjectsAndKeys:
//                                        categoryId, @"category_id",
//                                        [NSString stringWithFormat:@"%d", m_nCurrentPageNumber], @"page_number", 
//                                        [NSString stringWithFormat:@"%d", PAGE_SIZE_JOURNEY], @"page_size", nil];
//            
//            [[NetworkManager sharedNetworkManager] requestServerForMethod:NetworkRequest_GetJourneyNewsByCategoryId
//                                                           WithParameters:parameters
//                                                         AndCallBackScope:self
//                                                            AndSuccessSel:@"onSuccessForMore:"
//                                                             AndFailedSel:@"onFailedForMore:"];
//        }
//    }
//    else
//    {
        // 下拉
        [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
//    }
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
	[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:3.0];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view
{	
	return bIsLoading; // should return if data source model is reloading
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view
{	
	return [NSDate date]; // should return date data source was last changed
}

#pragma mark -
#pragma mark addLabelOnCell
-(void)addLabelOnCell:(UITableViewCell*)cell
				 text:(NSString*)text
				frame:(CGRect)frame 
			  bgColor:(UIColor*)bgColor 
			textColor:(UIColor*)textColor 
		   fontOfSize:(UIFont*)fontOfSize 
		lineBreakMode:(UILineBreakMode)lineBreakMode 
		textAlignment:(UITextAlignment)textAlignment
{
	if(!bgColor) bgColor = [UIColor grayColor];
	if(!textColor) textColor = [UIColor blackColor];
	if(!fontOfSize) fontOfSize = [UIFont systemFontOfSize:16];
	if(!text) text = [NSString stringWithString:@"请输入Label内容"];
	
	UILabel* titleLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
	titleLabel.backgroundColor = bgColor;
	titleLabel.textColor = textColor;
	titleLabel.font = fontOfSize;
	titleLabel.lineBreakMode = UILineBreakModeCharacterWrap;
	titleLabel.textAlignment = textAlignment;
	titleLabel.text = text;
	[cell.contentView addSubview:titleLabel];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
